package com.hospes.rmes.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
import com.hospes.rmes.App;
import com.hospes.rmes.constants.ConstMain;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by IntelliJ IDEA.
 * User: Andrew Khloponin
 * Date: 17.06.11
 */
public class Utils {

	private static String strFormat = "dd/MM/yyyy HH:mm";
	private static ConnectivityManager conMgr = (ConnectivityManager) App.context.getSystemService(Context.CONNECTIVITY_SERVICE);

	public static Date FromStringToDate(String strDate) {
		Date dateDate;
		SimpleDateFormat sdf = new SimpleDateFormat(strFormat, Locale.US);
		try {
			dateDate = sdf.parse(strDate);
		} catch (ParseException e) {
			dateDate = new Date();
			Log.e(ConstMain.LOG_TAG, "" + e.toString());
		}
		return dateDate;
	}

	public static String FromDateToString(Date dateDate) {
		SimpleDateFormat sdf = new SimpleDateFormat(strFormat, Locale.US);
		return sdf.format(dateDate);
	}

	public static String convertStreamToString(InputStream stream) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
		StringBuilder stringBuilder = new StringBuilder();
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				stringBuilder.append(line).append("\n");
			}
		} catch (IOException e) {
			Log.i(ConstMain.LOG_TAG, "Error converting stream", e);
		} finally {
			try {
				stream.close();
			} catch (IOException e) {
				Log.i(ConstMain.LOG_TAG, "Error closing stream", e);
			}
		}
		return stringBuilder.toString();
	}

	public static String getFileName(String url) {
		String result = "";
		if (url != null && url.length() > 0) {
			int slesh = url.lastIndexOf("/");
			if (slesh > 0 && slesh < url.length()) {
				result = url.substring(slesh + 1) + "ggg";
			}
		}
		if (result.equals("")) {
			result = url;
		}
		return result;
	}

	public static boolean isInternetConnected() {
		return conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected();
	}
}
